﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Web;
using System.Web.Mvc;
using KMF.Common;
using KMF.DAL;
using KMF.WebUI.Areas.KMFadmin.Attributes;
using KMF.WebUI.Areas.KMFadmin.CustomHelpers;
using KMF.WebUI.Areas.KMFadmin.Models;
using KMF.WebUI.Areas.KMFadmin.Infrastructure;

namespace KMF.WebUI.Areas.KMFadmin.Controllers
{
    [AdminLoggedAuthorize]
    public class AdminProductCategoryController : Controller
    {
        //
        // GET: /Admin/ProductCategory/
        #region Category
        
        public ActionResult Index()
        {
            var model = ProductCategoryDb.GetAllCateRoot() ?? new List<ProductCategoryDto>();
            ViewBag.ParentList = FunctionHelper.GetMenuListThreeLevel() ?? new List<ProductCategoryDto>();
            return View(model);
        }

        public ActionResult AddCategory()
        {
            ViewBag.ParentList = FunctionHelper.GetMenuListThreeLevel() ?? new List<ProductCategoryDto>();
            ViewBag.DiscountList = DiscountDb.GetDiscountApplyCategory() ?? new List<DiscountDto>();
            ViewBag.GiftList = GiftDb.GetGiftApplyCategory() ?? new List<GiftDto>();
            var model = new ProductCategoryDto
            {
                Active=true
            };
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AddCategory(ProductCategoryDto model, HttpPostedFileBase fileImagePath, int discountId = 0, int giftId = 0)
        {
            var error = string.Empty;
            var imagePath = string.Empty;
            var folderUpload = Server.MapPath(ConstParam.FolderUploadCategoryProductImage);
            if (fileImagePath != null) imagePath = FunctionHelper.UploadImages(out error, folderUpload, fileImagePath);
            model.ImagePath = imagePath;
            //model.Description = Server.HtmlEncode(model.Description);
            model.Id = FunctionHelper.GenerateId();
            ProductCategoryDb.Add(model);
            if (discountId > 0) DiscountApplyToCategoryDb.Add(new DiscountApplyToCategoryDto { DiscountId = discountId, CategoryId = model.Id });
            if (giftId > 0) GiftApplyToCategoryDb.Add(new GiftApplyToCategoryDto { GiftId = giftId, CategoryId = model.Id });

            ProductCategoryDb.UpdateBreadCrumb(model.Id, model.ParentId);
            return RedirectToAction("Index", "AdminProductCategory");
        }

        public ActionResult EditCategory(string id)
        {
            ViewBag.ParentList = FunctionHelper.GetMenuListThreeLevel() ?? new List<ProductCategoryDto>();

            ViewBag.DiscountList = DiscountDb.GetDiscountApplyCategory() ?? new List<DiscountDto>();
            ViewBag.GiftList = GiftDb.GetGiftApplyCategory() ?? new List<GiftDto>();
            ViewBag.GiftId = GiftDb.GetGiftIdByCategoryId(id);
            ViewBag.DiscountId = DiscountDb.GetDiscountIdByCategoryId(id);

            var model = ProductCategoryDb.GetById(id);
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditCategory(ProductCategoryDto model,HttpPostedFileBase fileImagePath)
        {
            var error = string.Empty;
            var imagePath = string.Empty;
            var folderUpload = Server.MapPath(ConstParam.FolderUploadCategoryProductImage);
            if (fileImagePath != null) imagePath = FunctionHelper.UploadImages(out error, folderUpload, fileImagePath);
            model.ImagePath = imagePath;
            var result = ProductCategoryDb.Update(model);
            result = ProductCategoryDb.UpdateBreadCrumb(model.Id, model.ParentId);
            if (result > 0) TempData["updateInfo"] = 1;
            else TempData["updateInfo"] = 0;
            ViewBag.ParentList = FunctionHelper.GetMenuListThreeLevel() ?? new List<ProductCategoryDto>();
            //return View(model);
            return RedirectToAction("Index", "AdminProductCategory");
        }

        public JsonResult GetCateChildList(string id)
        {
            var data = ProductCategoryDb.GetAllByParentIdAdmin(id) ?? new List<ProductCategoryListAdminDto>();


            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public JsonResult DeleteCategory(string id)
        {
            var result = ProductCategoryDb.DeleteById(id);
            if (result <= 0) return Json(false, JsonRequestBehavior.AllowGet);
            return Json(true, JsonRequestBehavior.AllowGet);
        }

        public ActionResult CategoryBanner(int page = 1)
        {
            var itemsPerPage = int.Parse(ConfigurationManager.AppSettings["DefaultItemsPerPage"]);
            var totalPage = 0;
            var totalRecord = 0;
            var model = ProductCategoryBannerDb.GetAllCategoryBanner(page, itemsPerPage, ref totalPage, ref totalRecord) ?? new List<ProductCategoryBannerAdminListDto>();

            ViewBag.PageInfo = new PageInfo { CurrentPage = page, PageSize = itemsPerPage, TotalPages = totalPage };
            ViewBag.TotalRecord = totalRecord;
            ViewBag.MenuList = FunctionHelper.GetMenuListThreeLevel() ?? new List<ProductCategoryDto>();
            return View(model);
        }

        //Add banner category
        public ActionResult CategoryBannerAdd()
        {
            ViewBag.ParentList = FunctionHelper.GetMenuListThreeLevel() ?? new List<ProductCategoryDto>();
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CategoryBannerAdd(ProductCategoryBannerDto model, HttpPostedFileBase fileImagePath)
        {
            var error = string.Empty;
            var imagePath = string.Empty;
            var fPath = ConstParam.FolderUploadCategoryProductImage;
            var folderUpload = Server.MapPath(fPath);
            if (fileImagePath != null && !string.IsNullOrEmpty(fileImagePath.FileName)) imagePath = FunctionHelper.UploadImages(out error, folderUpload, fileImagePath);
            if (!string.IsNullOrEmpty(imagePath))
            {
                model.ImagePath = fPath + imagePath;
            }
            model.CreateDate = DateTime.Now;
            if (model.BeginDate == DateTime.MinValue)
            {
                model.BeginDate = DateTime.MinValue;
            }
            if (model.EndDate == DateTime.MinValue)
            {
                model.EndDate = DateTime.MaxValue;
            }
            ProductCategoryBannerDb.Add(model);
            return RedirectToAction("CategoryBanner", "ProductCategory");
        }

        //Edit banner category
        public ActionResult CategoryBannerEdit(int id)
        {
            ViewBag.ParentList = FunctionHelper.GetMenuListThreeLevel() ?? new List<ProductCategoryDto>();
            var model = ProductCategoryBannerDb.GetById(id) ?? new ProductCategoryBannerDto();
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CategoryBannerEdit(ProductCategoryBannerDto model, HttpPostedFileBase fileImagePath)
        {
            var error = string.Empty;
            var imagePath = string.Empty;
            var fPath = ConstParam.FolderUploadCategoryProductImage;
            var folderUpload = Server.MapPath(fPath);
            if (fileImagePath != null && !string.IsNullOrEmpty(fileImagePath.FileName)) imagePath = FunctionHelper.UploadImages(out error, folderUpload, fileImagePath);
            if (!string.IsNullOrEmpty(imagePath))
            {
                model.ImagePath = fPath + imagePath;
            }
            model.CreateDate = DateTime.Now;
            if (model.BeginDate == DateTime.MinValue)
            {
                model.BeginDate = DateTime.MinValue;
            }
            if (model.EndDate == DateTime.MinValue)
            {
                model.EndDate = DateTime.MaxValue;
            }
            ProductCategoryBannerDb.Update(model);
            return RedirectToAction("CategoryBanner", "AdminProductCategory");
        }

        public JsonResult CategoryBannerDel(int id)
        {
            var result = ProductCategoryBannerDb.Delete(id);
            var data = new { id, result };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public PartialViewResult CategoryBannerGetByCate(string categoryId)
        {
            var model = ProductCategoryBannerDb.GetByCate(categoryId) ?? new List<ProductCategoryBannerAdminListDto>();
            return PartialView(model);
        }

        public JsonResult UpdateDiscountApplyCate(int discountId, string categoryId)
        {
            DiscountDb.DeleteDiscountApplyCategory(categoryId);
            var result = DiscountApplyToCategoryDb.Add(new DiscountApplyToCategoryDto { DiscountId = discountId, CategoryId = categoryId });
            return Json(result > 0, JsonRequestBehavior.AllowGet);
        }

        public JsonResult UpdateGiftApplyCate(int giftId, string categoryId)
        {
            GiftDb.DeleteGiftApplyToCategory(categoryId);
            var result = GiftApplyToCategoryDb.Add(new GiftApplyToCategoryDto { GiftId = giftId, CategoryId = categoryId });
            return Json(result > 0, JsonRequestBehavior.AllowGet);
        }

        public JsonResult DeleteDiscountApplyCategory(int discountId, string categoryId)
        {
            var result = DiscountApplyToCategoryDb.Delete(discountId, categoryId);
            var model = new { Data = result > 0, DiscountId = discountId };
            return Json(model, JsonRequestBehavior.AllowGet);
        }

        public JsonResult DeleteGiftApplyCategory(int giftId, string categoryId)
        {
            var result = GiftApplyToCategoryDb.Delete(giftId, categoryId);
            var model = new { Data = result > 0, GiftId = giftId };
            return Json(model, JsonRequestBehavior.AllowGet);
        }
        
        #endregion

        #region Template To category

        public PartialViewResult CateTemplate(string cateId)
        {
            ViewBag.CateTemplateList = ProductCateTempMappingDb.GetByCateId(cateId) ?? new List<ViewProductCateTempMappingDto>();
            ViewBag.TemplateList = CommonHelpers.CreateListHasDefaultName(TemplateDb.GetAll() ?? new List<TemplateDto>(), "Id", "Description", -1, "--");
            ViewBag.CateId = cateId;
            return PartialView();
        }

        [HttpPost]
        public JsonResult CateTemplate(ProductCateTempMappingDto model)
        {
            var resultId = ProductCateTempMappingDb.Add(model);
            var data = new { Id = resultId, Success = resultId > 0  };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public PartialViewResult GetCateTemplate(int id, string currentDate = "")
        {
            var model = ProductCateTempMappingDb.GetById(id) ?? new ViewProductCateTempMappingDto();
            return PartialView(model);
        }

        public JsonResult DeleteCateTemplate(int id)
        {
            var result = ProductCateTempMappingDb.Delete(id);
            var data = new { Id = id, Success = result > 0 };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public PartialViewResult EditCateTemplate(int id)
        {
            var model = ProductCateTempMappingDb.GetSingleById(id) ?? new ProductCateTempMappingDto();
            ViewBag.TemplateList = CommonHelpers.CreateListHasDefaultName(TemplateDb.GetAll() ?? new List<TemplateDto>(), "Id", "Description", -1, "--");
            return PartialView(model);
        }

        [HttpPost]
        public JsonResult EditCateTemplate(ProductCateTempMappingDto model)
        {
            var result = ProductCateTempMappingDb.Update(model);
            var item = ProductCateTempMappingDb.GetById(model.Id);
            var data = new { Item = item, Success = result > 0 };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #region Sub Template to category

        public PartialViewResult SubTemplateCate(string categoryId = "", string currentDate = "")
        {
            ViewBag.CateTemplateList = CommonHelpers.CreateListHasDefaultName(ProductCateTempMappingDb.GetAllByCateId(categoryId) ?? new List<ProductCateTempMappingDto>(), 
                                    "Id", "Description", -1, "--");
            ViewBag.CategoryId = categoryId;
            return PartialView();
        }

        [HttpPost]
        [ValidateInput(false)]
        public JsonResult SubTemplateCate(SubCategoryTemplateDto model)
        {
            var resultId = SubCategoryTemplateDb.Add(model);
            var data = new { Id = resultId, Success = resultId > 0 };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public PartialViewResult GetSubCateTemplateItem(int id, string categoryId, string currentDate)
        {
            var model = SubCategoryTemplateDb.GetByIdJoin(id) ?? new ViewSubCategoryTempJoinDto();
            ViewBag.CategoryId = categoryId;
            return PartialView(model);
        }

        public PartialViewResult GetSubCateTemplateList(int productCateTempMappingId, string categoryId, string currentDate)
        {
            var model = SubCategoryTemplateDb.GetAllByMappingId(productCateTempMappingId) ?? new List<ViewSubCategoryTempJoinDto>();
            ViewBag.CategoryId = categoryId;
            return PartialView(model);
        }

        public PartialViewResult EditSubCateTemplate(int id, string categoryId)
        {
            ViewBag.CateTemplateList = CommonHelpers.CreateListHasDefaultName(ProductCateTempMappingDb.GetAllByCateId(categoryId) ?? new List<ProductCateTempMappingDto>(),
                                    "Id", "Description", -1, "--");
            var model = SubCategoryTemplateDb.GetById(id) ?? new SubCategoryTemplateDto();
            return PartialView(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public JsonResult EditSubCateTemplate(SubCategoryTemplateDto model)
        {
            var result = SubCategoryTemplateDb.Update(model);
            var data = new { Id = model.Id, Success = result > 0 };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        public JsonResult DeleteSubCateTemplate(int id)
        {
            var resultId = SubCategoryTemplateDb.Delete(id);
            var data = new { Id = id, Success = resultId > 0 };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

    

        #endregion

        #region Template category

        public ActionResult TemplateList(int currentPage = 1)
        {
            int itemsPerPage = int.Parse(ConfigurationManager.AppSettings["DefaultItemsPerPage"]);
            int totalPage = 0;
            var model = TemplateDb.GetAllPaging(currentPage, itemsPerPage, ref totalPage) ?? new List<ViewCateTemplatePagingDto>();
            ViewBag.PageInfo = new PageInfo { CurrentPage = currentPage, PageSize = itemsPerPage, TotalPages = totalPage };
            return View(model);
        }

        public ActionResult AddTemplateCategory()
        {
            return View();
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AddTemplateCategory(TemplateDto model)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("ErrorSummary", "Đã có lỗi xảy ra!");
                return View(model);
            }

            var result = TemplateDb.Add(model);
            if (result > 0) return RedirectToAction("EditTemplateCategory", new {id = result});

            ModelState.AddModelError("ErrorSummary", "Đã có lỗi xảy ra!");
            return View(model);
        }

        public ActionResult EditTemplateCategory(int id)
        {
            var model = TemplateDb.GetById(id) ?? new TemplateDto();
            return View(model);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditTemplateCategory(TemplateDto model)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("ErrorSummary", "Đã có lỗi xảy ra!");
                return View(model);
            }

            var result = TemplateDb.Update(model);

            if (result > 0) return View(model);

            ModelState.AddModelError("ErrorSummary", "Đã có lỗi xảy ra!");
            return View(model);
        }

        public JsonResult DeleteTemplateCategory(int id)
        {
            var result = TemplateDb.Delete(id);
            return Json(result > 0, JsonRequestBehavior.AllowGet);
        }

        #endregion Template category
    }
}
